import sqlite3
import os
from datetime import datetime

class Database:
    def __init__(self):
        db_path = os.path.join(os.path.expanduser('~'), 'AppData', 'Local', 'AssessmentFee', 'history.db')
        os.makedirs(os.path.dirname(db_path), exist_ok=True)
        self.conn = sqlite3.connect(db_path, check_same_thread=False)
        self.create_table()

    def create_table(self):
        cursor = self.conn.cursor()
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                type TEXT,
                amount REAL,
                original REAL,
                discount TEXT,
                result REAL,
                timestamp DATETIME
            )
        ''')
        self.conn.commit()

    def add_record(self, calc_type, amount, original, discount, result):
        try:
            timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            cursor = self.conn.cursor()
            cursor.execute('''
                INSERT INTO history (type, amount, original, discount, result, timestamp)
                VALUES (?, ?, ?, ?, ?, ?)
            ''', (calc_type, amount, original, discount, result, timestamp))
        except sqlite3.Error as e:
            print(f"数据库写入错误: {str(e)}")
            self.conn.rollback()
        else:
            self.conn.commit()
        finally:
            if self.conn:
                self.conn.close()

    def get_history(self):
        cursor = self.conn.cursor()
        cursor.execute('SELECT type, amount, original, discount, result, timestamp FROM history ORDER BY timestamp DESC')
        return cursor.fetchall()

    def delete_all_records(self):
        try:
            cursor = self.conn.cursor()
            cursor.execute('DELETE FROM history')
            self.conn.commit()
        except sqlite3.Error as e:
            print(f"清空记录失败: {str(e)}")
            self.conn.rollback()
        finally:
            if self.conn:
                self.conn.close()

    def __del__(self):
        if hasattr(self, 'conn'):
            self.conn.close()